﻿using System;
using System.Collections.Generic;
using AutoMapper;
using Budget.Core.Data;
using Budget.Core.DomainModel;
using Budget.Core.Extensions;
using Budget.Core.Specifications;
using Budget.Wcf.Core.Dto;
using Budget.Wcf.Core.Interfaces;
using Castle.Core.Logging;

namespace Budget.Wcf.Services
{
    public class BalanceService : BaseService, IBalanceService
    {
        private readonly IRepository<Balance> balanceRepo;

        public BalanceService(ILogger logger, IRepository<Balance> balanceRepo)
            : base(logger)
        {
            this.balanceRepo = balanceRepo;
        }

        public IList<BalanceData> GetBalances()
        {
            try
            {
                var balances = balanceRepo.Find.All();
                var balancesData = Mapper.Map<IList<Balance>, IList<BalanceData>>(balances);
                return balancesData;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Details());

                return null;
            }
        }

        public void SetBalance(BalanceData balanceData)
        {
            try
            {
                var dbBalance = Mapper.Map<BalanceData, Balance>(balanceData);
                balanceRepo.SaveOrUpdate(dbBalance);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Details());
            }
        }

        public decimal GetCurrentBalance()
        {
            try
            {
                var lastBalance = balanceRepo.Find.One(BalanceSpecifications.Latest());
                return lastBalance != null
                           ? lastBalance.CalculateBalance()
                           : 0;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Details);

                return 0;
            }
        }
    }
}